package com.hxfeng.authdemo.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hxfeng.authdemo.entity.MyUser;
import com.hxfeng.authdemo.entity.User;
import com.hxfeng.authdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;


@Component
public class UserAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserMapper userDetailsService;

    /**
     * 身份验证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal(); // 获取用户名
        String password = (String) authentication.getCredentials(); // 获取密码
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UsernameNotFoundException("用户名或密码不能为空");
        }
        User user = userDetailsService.selectById(Long.parseLong(username));
        MyUser sysUserDetails = new MyUser();
        sysUserDetails.setUsername(user.getUserId().toString());
        sysUserDetails.setPassword(user.getPassword());
        Set<GrantedAuthority> strings = new HashSet<>();
        strings.add(new SimpleGrantedAuthority("hello"));
        sysUserDetails.setAuthorities(strings);

        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        if (!getPasswordEncoder().matches(password, sysUserDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return new UsernamePasswordAuthenticationToken(sysUserDetails, password, sysUserDetails.getAuthorities());

    }

    /**
     * 支持指定的身份验证
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
